#include "citycodeacq.h"

#include <QFile>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

CityCodeAcq::CityCodeAcq()
{

}

void CityCodeAcq::InitCityMap()
{
    QFile file(":/citycode.json");
    if(!file.open(QIODevice::ReadOnly))
        return;
    QByteArray rawData = file.readAll();
    QJsonDocument jsonDocument = QJsonDocument::fromJson(rawData);
    if(jsonDocument.isArray())
    {
        QJsonArray jsonArray = jsonDocument.array();
        for(QJsonValue value : jsonArray)
        {
            if(value.isObject())
            {
                QString cityName = value["city_name"].toString();
                QString cityCode = value["city_code"].toString();
                cityMap.insert(cityName,cityCode);
            }
        }
    }
}

QString CityCodeAcq::getCityCodefromName(QString cityName)
{
    //cityMap为空进行初始化，添加数据
    if(cityMap.isEmpty())
    {
        InitCityMap();
    }

    //不为空寻找对应城市名称的城市代码。
    auto it = cityMap.find(cityName);
    if( it == cityMap.end())
    {
        //找西安找不到，找西安市
        it = cityMap.find(cityName+"市");
        //找西安市找不到，找西安县
        if(it == cityMap.end())
        {
            it = cityMap.find(cityName+"县");
        }

        if(it == cityMap.end())
        {
            it = cityMap.find(cityName+"区");
        }

        if(it == cityMap.end())
        {
            return "";
        }
    }
    return it.value();
}
